<?php


namespace app\api\controller;


use addons\epay\library\Service;
use app\admin\model\Qunorder;
use app\common\controller\Api;

class Order extends Api
{
    protected $noNeedLogin = ['notifyx'];
    protected $noNeedRight = ['*'];

    # 获取订单记录
    public function getList()
    {
        $result = DB('quan_order')->where('user_id',$this->auth->id)->order('id desc')->paginate(10);
        $total = $result->total();
        $lastpage = $result->lastPage();
        $rows = $result->items();
        $data = [];
        $status_arr = [
            0=>'待支付',
            1=>'已支付',
            -1=>'订单关闭',
        ];
        foreach ($rows as $v){
            $qun = DB('qun_list')->where('id',$v['qun_id'])->find();
            $data[] = [
                'id'=>$v['id'],
                'qun_name'=>$qun['name'],
                'qun_id'=>$v['qun_id'],
                'qun_descript'=>$qun['descript'],
                'qun_image'=>cdnurl($qun['image']),
                'order_sn'=>$v['order_sn'],
                'money'=>$v['money'],
                'status'=>$v['status'],
                'status_name'=>$status_arr[$v['status']],
                'pay_time'=>empty($v['pay_time'])?'':date('Y-m-d H:i:s',$v['pay_time']),
            ];
        }
        $this->success('获取成功',[
            'total'=>$total,
            'lastpage'=>$lastpage,
            'list'=>$data,
        ]);
    }

    # 获取直推订单
    public function getListByzhitui()
    {

        $result = DB('quan_order')->where('zhitui_id',$this->auth->id)->order('id desc')->paginate(10);
        $total = $result->total();
        $lastpage = $result->lastPage();
        $rows = $result->items();
        $data = [];
        $status_arr = [
            0=>'待支付',
            1=>'已支付',
            -1=>'订单关闭',
        ];
        foreach ($rows as $v){
            $qun = DB('qun_list')->where('id',$v['qun_id'])->find();
            $data[] = [
                'id'=>$v['id'],
                'qun_id'=>$v['qun_id'],
                'qun_name'=>$qun['name'],
                'qun_descript'=>$qun['descript'],
                'qun_image'=>cdnurl($qun['image']),
                'order_sn'=>$v['order_sn'],
                'money'=>$v['money'],
                'status'=>$v['status'],
                'status_name'=>$status_arr[$v['status']],
                'pay_time'=>empty($v['pay_time'])?'':date('Y-m-d H:i:s',$v['pay_time']),
            ];
        }
        $this->success('获取成功',[
            'total'=>$total,
            'lastpage'=>$lastpage,
            'list'=>$data,
        ]);
    }
    # 获取间推订单
    public function getListByjiantui()
    {


        $result = DB('quan_order')->where('jiantui_id',$this->auth->id)->order('id desc')->paginate(10);
        $total = $result->total();
        $lastpage = $result->lastPage();
        $rows = $result->items();
        $data = [];
        $status_arr = [
            0=>'待支付',
            1=>'已支付',
            -1=>'订单关闭',
        ];
        foreach ($rows as $v){
            $qun = DB('qun_list')->where('id',$v['qun_id'])->find();
            $data[] = [
                'id'=>$v['id'],
                'qun_id'=>$v['qun_id'],
                'qun_name'=>$qun['name'],
                'qun_descript'=>$qun['descript'],
                'qun_image'=>cdnurl($qun['image']),
                'order_sn'=>$v['order_sn'],
                'money'=>$v['money'],
                'status'=>$v['status'],
                'status_name'=>$status_arr[$v['status']],
                'pay_time'=>empty($v['pay_time'])?'':date('Y-m-d H:i:s',$v['pay_time']),
            ];
        }
        $this->success('获取成功',[
            'total'=>$total,
            'lastpage'=>$lastpage,
            'list'=>$data,
        ]);
    }
    # 获取支付前页面
    public function getJisuan()
    {
        $qun_id = $this->request->param('qun_id', 0);
        $is_buy = 0;
        $qun = DB('qun_list')->where('id',$qun_id)->find();
        if(empty($qun)){
            $this->error('参数错误');
        }
        $info = Db('quan_order')->where('user_id',$this->auth->id)->where('qun_id',$qun_id)->where('status',1)->find();
        if(!empty($info)){
            $is_buy = 1;
        }
        $list = DB('qun_zi')->where('qun_id',$qun_id)->field('id,name,image,nums')->where('status',0)->select();
        foreach ($list as &$v){
            $v['image'] = cdnurl($v['image']);
            $v['name'] .='(已满)' ;
        }
        $title = '群已加满';
        $info = DB('qun_zi')->where('qun_id',$qun_id)->where('status',1)->field('id,name,image,qun_image')->find();
        $title = '请进'.$info['name'].' 长按下方二维码入群';
        if(!empty($info)){
            $info['image'] = cdnurl($info['image']);
            $info['qun_image'] = $is_buy==0?'':cdnurl($info['qun_image']);
        }
        $this->success('获取成功',[
            'title'=>$title,
            'quanyi_image'=>cdnurl(DB('config')->where('name','quany_image')->value('value')),
            'list'=>$list,
            'info'=>$info,
            'is_buy'=>$is_buy,
        ]);

    }

//    # 判断是否支付
//    public function checkPay()
//    {
//        $order_id = $this->request->param('order_id');
//
//    }

    # 创建订单
    public function createOrder()
    {
        $qun_id = $this->request->param('qun_id', 0);
        $order_sn = date("YmdHis") . mt_rand(100000, 999999);
        $qun = DB('qun_list')->where('id',$qun_id)->find();
        if(empty($qun)){
            $this->error('参数错误');
        }
        $info = Db('quan_order')->where('user_id',$this->auth->id)->where('qun_id',$qun_id)->where('status',1)->find();
        if(!empty($info)){
            $this->error('请勿重复支付');
        }
        $zhitui_id = $this->auth->zhitui_id;
        $jiantui_id = 0;
        $zhitui_price = 0;
        $jiantui_price = 0;
        $money = $qun['price'];
        if(!empty($zhitui_id)){
            $zhitui = \app\common\model\User::get($zhitui_id);
            if(!empty($zhitui)){
                       $jiantui_id = $zhitui->zhitui_id;
            $zhitui_bfb = DB('config')->where('name','zhitui_bfb')->value('value');
            $zhitui_price = round($money*$zhitui_bfb,2);
            if($jiantui_id){
                $jiantui_bfb = DB('config')->where('name','jiantui_bfb')->value('value');
                $jiantui_price = round($money*$jiantui_bfb,2);
            }
            }
     
        }
        $data = [
            'user_id'=>$this->auth->id,
            'qun_id'=>$qun_id,
            'order_sn'=>$order_sn,
            'money'=>$qun['price'],
            'openid'=>$this->auth->mp_openid,
            'createtime'=>time(),
            'zhitui_id'=>$zhitui_id,
            'zhitui_price'=>$zhitui_price,
            'jiantui_id'=>$jiantui_id,
            'jiantui_price'=>$jiantui_price,
        ];
        $order_id = DB('quan_order')->insertGetId($data);
        $this->success('获取成功',['order_id'=>$order_id]);

    }

    # 获取支付参数
    public function pay()
    {
        $id = $this->request->post('order_id', 0);
        if(!$id){
            $this->error('订单ID不存在');
        }
        $order = \app\admin\model\Qunorder::where('id',$id )->find();
        if(empty($order)){
            $this->success('订单不存在',$order->id);
        }
        $amount = $order->money;
        $type = 'wechat';
        $method = 'mp';
        $openid = $order->openid;
        $order->order_sn = date("YmdHis") . mt_rand(100000, 999999);
        $order->save();
        //订单号
        $out_trade_no = $order->order_sn ;
        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型不能为空");
        }

        if (in_array($method, ['miniapp', 'mp']) && !$openid) {
            $this->error("openid不能为空");
        }

        //订单标题
        $title = '订单支付';

        //回调链接
        $notifyurl = $this->request->root(true) . '/api/order/notifyx/paytype/' . $type;
        $returnurl = $this->request->root(true) . '/api/order/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;

        $response = Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method, $openid);

        return $this->success('获取成功',$response) ;
    }

    /**
     * 支付成功，仅供开发测试
     */
    public function notifyx()
    {
        writelog('111111111','pay.txt');
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();

        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }


            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            writelog($out_trade_no,'pay.txt');
            $pay = Qunorder::where('order_sn',$out_trade_no)->find();
            if($pay->status==0){
                $pay->pay_time = time();
                $pay->status = 1;
                $pay->pay_fee = $payamount;
                $pay->save();
                if($pay->zhitui_id && $pay->zhitui_price){
                    \app\common\model\User::money($pay->zhitui_price,$pay->zhitui_id,'直推奖');
                }
                if($pay->jiantui_id && $pay->jiantui_price){
                    \app\common\model\User::money($pay->jiantui_price,$pay->jiantui_id,'间推奖');
                }
            }

            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            //你可以在此编写订单逻辑
        } catch (Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }

    /**
     * 支付返回，仅供开发测试
     */
    public function returnx()
    {
        $paytype = $this->request->param('paytype');
        $out_trade_no = $this->request->param('out_trade_no');
        $pay = Service::checkReturn($paytype);
        if (!$pay) {
            $this->error('签名错误', '');
        }

        //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
        $this->success("请返回网站查看支付结果", addon_url("epay/index/index"));
    }
}